import React, { useState } from 'react';
import { analyzeEmotion } from '../services/api';

interface TextEmotionAnalyzerProps {
  onTextChange: (text: string) => void;
  onEmotionAnalyze: (emotion: string) => void;
  loading: boolean;
  setLoading: (loading: boolean) => void;
}

const TextEmotionAnalyzer: React.FC<TextEmotionAnalyzerProps> = ({
  onTextChange,
  onEmotionAnalyze,
  loading,
  setLoading
}) => {
  const [text, setText] = useState('');

  const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const value = e.target.value;
    setText(value);
    onTextChange(value);
  };

  const handleAnalyze = async () => {
    if (!text.trim()) return;

    setLoading(true);
    try {
      // 调用后端情绪分析API
      const result = await analyzeEmotion(text);

      if (result.success) {
        onEmotionAnalyze(result.data.emotion);
      } else {
        throw new Error(result.error || '情绪分析失败');
      }
    } catch (error: any) {
      console.error('情绪分析失败:', error);
      alert(`情绪分析失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="mb-8">
      <h2 className="text-xl font-semibold mb-4">输入你的文字</h2>
      <textarea
        value={text}
        onChange={handleTextChange}
        placeholder="写下你此刻的想法或感受..."
        className="w-full h-32 p-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
      />
      <div className="mt-4 flex justify-end">
        <button
          onClick={handleAnalyze}
          disabled={loading || !text.trim()}
          className={`px-6 py-2 rounded-md ${
            loading || !text.trim()
              ? 'bg-gray-400 cursor-not-allowed'
              : 'bg-indigo-600 text-white hover:bg-indigo-700 transition'
          }`}
        >
          {loading ? '分析中...' : '分析情绪'}
        </button>
      </div>
    </div>
  );
};

export default TextEmotionAnalyzer;